package com.example.permission.myjbm.activitys;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.jbmsuppliers.R;
import com.example.jbmsuppliers.sinopec.view.DialogLoading;
import com.example.permission.myjbm.dao.BaseAty;
import com.example.permission.myjbm.entity.Emp;
import com.example.permission.myjbm.net.ReleaseNet;
import com.example.permission.myjbm.utils.ScreenAsset;
import com.example.weather.myframe.PopupSelectImage;
import com.jbm.jbmsupplier.util.GeoInfoEntity;
import com.jbm.jbmsupplier.util.ICtrl;
import com.jbm.jbmsupplier.util.InfoAttachmentEntity;
import com.jbm.jbmsupplier.util.InfomationEntity;
import com.squareup.picasso.Picasso;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 发布商品页面
 */

public class Release_Commodity_1 extends BaseAty implements View.OnClickListener{
    private int category;
        private ImageView back;
    private TextView send,header_title;
    private TextView release_select_address;
    private EditText release_desc;
    private TextView release_send_price;
    private ReleaseNet net;
    private Intent intent;
    private int screenWidth;
    private List<GeoInfoEntity> scopeList;
    private  List<InfoAttachmentEntity> attList;
    private int photoIndex;
    private DialogLoading loader;
    //请求码
    private final int  PHOTO=100;
    private final int  SELECTADDRESS=101;
    private String title="发布商品";


    public Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
           switch(msg.what){
               case  ReleaseNet.RELEASEERROR:
                   ICtrl ictrl = (ICtrl) msg.obj;
                   if(ictrl.back==true){
                       loader.setTextstr("上传完成");
                       finish();
                   }else{
                       hint(ictrl.errorinfo);
                       loader.setTextstr(ictrl.errorinfo);
                   }
                   loader.dismiss();
                   break;
           }

        }
    };



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.release__commodity_1);
        initData();
        intiView();
    }

//初始化数据
    private void initData() {
        category= getIntent().getIntExtra("category",1);
        intent=new Intent(Release_Commodity_1.this, PopupSelectImage.class);
        screenWidth=ScreenAsset.getScreenWidth(Release_Commodity_1.this);
       net =new ReleaseNet(handler);
        //要传入接口的地址数据
         scopeList=new ArrayList<>();
//        //要传入接口的图片数据
        attList=new ArrayList<>();
        loader=new DialogLoading(this);


    }

    //初始化组件
    private void intiView() {
        //返回
        back=(ImageView)findViewById(R.id.header_back);
        //发送
       send=(TextView)findViewById(R.id.header_right);
        //选择地址
        release_select_address= (TextView)findViewById(R.id.release_select_address);
        //描述
        release_desc= (EditText)findViewById(R.id.release_desc);
        //发布价格
        release_send_price= (TextView)findViewById(R.id.release_send_price);

        header_title=(TextView)findViewById(R.id.header_title);

        switch (category){
            case 1:
                title="发布商品";
                break;
            case 2:
            case 4:
            case 6:
                title="发布信息";
                break;
        }
        header_title.setText(title);
        if(category!=1){
            release_send_price.setVisibility(View.GONE);
        }
        initListener();
    }
    //初始化监听
    private void initListener() {
        back.setOnClickListener(this);
        send.setOnClickListener(this);
        release_select_address.setOnClickListener(this);

        addDeleteImg();
    }
   private  ArrayList<Emp> arrEmp;
  private  MyGrid adapter;

    /**
     * 添加和删除图片的操作
     */
    public void addDeleteImg(){
        arrEmp=new ArrayList<Emp>();
        arrEmp.add(new Emp(0,null));
        GridView gd = (GridView) findViewById(R.id.ceshi_grid);
        adapter=new MyGrid();
        gd.setAdapter(adapter);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.header_back:
                Release_Commodity_1.this.finish();
                break;
            case R.id.header_right:
                sendRequest();
                break;
            case R.id.release_select_address:
                Intent intent1=new Intent(Release_Commodity_1.this,DSYSelectAddress.class);
                startActivityForResult(intent1,101);
                break;

        }
    }

       //发布商品  调用服务器接口
    private void sendRequest() {

        InfomationEntity obj=new InfomationEntity();
        obj.setIsvip(0);
        obj.setIsdel(0);
        obj.setTypeId(category);
        obj.setContent(release_desc.getText().toString());
        obj.setPhoneModule(android.os.Build.MODEL);
        obj.setStatus(1);
        //地址数据
        obj.setScopeList(scopeList);

        if(scopeList==null||scopeList.size()==0){
            hint("请选择地址");
            return;
        }

        if(arrEmp.size()!=1||release_desc.getText().toString().length()>0){
            loader.show();
            loader.setTextstr("正在上传...");
            //图片数据
            for(int i=0;i<arrEmp.size();i++){
                if(arrEmp.get(i).getType()==1){
                    InfoAttachmentEntity infos = new InfoAttachmentEntity();
                    infos.setAttType("pic");
                    infos.setPicByte(getFileToByte(arrEmp.get(i).getFile()));
                    infos.setAttOrgname(arrEmp.get(i).getFile().getName());
                    attList.add(infos);
                }
            }
            obj.setAttList(attList);
            net.sendRelease(obj);
        }else{
            hint("请发布内容或图片");
        }




    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode!=RESULT_OK){
            return;
        }
        switch(requestCode){
            //选择图片回调
            case PHOTO:
                File file = (File) data.getSerializableExtra("file");
                arrEmp.remove(arrEmp.size()-1);
                arrEmp.add(new Emp(1,file));
                if(arrEmp.size()<3){
                    arrEmp.add(new Emp(0,null));
                }
                adapter.notifyDataSetChanged();

                break;
            //选择地址回掉
            case SELECTADDRESS:
                release_select_address.setText("选择地址     "+data.getStringExtra("address"));
                ArrayList<String> sj = data.getStringArrayListExtra("data");
                scopeList.clear();
            for(int i=0;i<sj.size();i++){
                scopeList.add(new GeoInfoEntity(Integer.parseInt(sj.get(i))));
            }
                break;
        }
    }

    public  byte[] getFileToByte(File file) {
        byte[] by = new byte[(int) file.length()];
        try {
            InputStream is = new FileInputStream(file);
            ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
            byte[] bb = new byte[2048];
            int ch;
            ch = is.read(bb);
            while (ch != -1) {
                bytestream.write(bb, 0, ch);
                ch = is.read(bb);
            }
            by = bytestream.toByteArray();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return by;
    }

    /**
     * GridView的适配器
     */
    class MyGrid extends BaseAdapter{

        @Override
        public int getCount() {
            return arrEmp.size();
        }

        @Override
        public Object getItem(int position) {
            return arrEmp.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            MyHoler holder=null;
            if(convertView==null){
                convertView =View.inflate(Release_Commodity_1.this,R.layout.dsy_ceshi,null);
                holder=new MyHoler(convertView);
                convertView.setTag(holder);
            }else{
                holder=(MyHoler)convertView.getTag();
            }

            if(arrEmp.get(position).getType()==0){
                Picasso.with(Release_Commodity_1.this).load(R.mipmap.add_img).resize(screenWidth/5,screenWidth/5).into(holder.img);
                holder.delete.setVisibility(View.GONE);
                holder.img.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivityForResult(intent,PHOTO);
                    }
                });
            }else{
                Picasso.with(Release_Commodity_1.this).load(arrEmp.get(position).getFile()).resize(screenWidth/5,screenWidth/5).into(holder.img);
                holder.img.setClickable(false);
                holder.delete.setVisibility(View.VISIBLE);
                holder.delete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        arrEmp.remove(position);
                        if(arrEmp.size()<4){
                            if(arrEmp.get(arrEmp.size()-1).getType()!=0){
                                arrEmp.add(new Emp(0,null));
                            }
                        }
                        notifyDataSetChanged();
                    }
                });
            }

            return convertView;
        }
        class MyHoler{
            ImageView delete,img;
            public MyHoler(View convertView){
                   delete= (ImageView)convertView.findViewById(R.id.select_delete);
                   img= (ImageView)convertView.findViewById(R.id.selectImg);
            }
        }
    }
}
